<?php
// +----------------------------------------------------------------------
// |ZBPHP[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2019 http://www.benbenwangluo.com
// +----------------------------------------------------------------------
// | Author 似水星辰 [ 2630481389@qq.com ]
// +----------------------------------------------------------------------
// | 中犇软件 技术六部 出品
// +----------------------------------------------------------------------

namespace app\order\admin;

use app\admin\admin\Base;

use app\order\model\OrderRefund as RefundModel;
use app\common\model\Order as OrderModel;
use app\order\model\OrderInfo;
use think\Db;
/**
 * 订单售后
 * @package app\Refund\admin
 */
class Refund extends Base
{    
    
    /**
     * 订单售后
     * @return mixed
     */
    public function refund()
    {
       cookie('__forward__', $_SERVER['REQUEST_URI']);
        $server_no = input('param.server_no');
        $status = input('param.status', "0");
        $status = $status ? $status : "0";
        $sku_id = input('param.sku_id', "");
        $goods_id = input('param.goods_id', 0);
         
        $this->assign('status', $status);
        $refund_time = input('param.refund_time');
        $order_sn = input('param.order_sn');

        if ($order_sn) {
            $map[] = ['order_refund.order_sn', 'like', '%'.$order_sn.'%'];
        }
        if ($server_no) {
            $map[] = ['order_refund.server_no', '=', $server_no];
        }
        if ($refund_time) {
            $map[] = ['order_refund.create_time', '>=', strtotime($refund_time)];
            $map[] = ['order_refund.create_time', '<', (strtotime($refund_time . ' 23:59:59'))];
        }
        if ($goods_id) {
            $map[] = ['order_refund.goods_id', '=', $goods_id];
        }
        if ($sku_id !== "") {
            $map[] = ['order_refund.sku_id', '=',  $sku_id];
        }
        if($status !== "all"){
            $map[] = ['order_refund.status', '=', $status];
        }   

        // 排序
        $order = 'order_refund.create_time desc';
        // 数据列表
        $tab[] = ['title' => '全部', 'url' => url('refund', 'status=all'), 'value' => "all"];
        $tab[] = ['title' => '售后申请', 'url' => url('refund', 'status=0'), 'value' => "0"];
        $tab[] = ['title' => '售后同意', 'url' => url('refund', 'status=1'), 'value' => '1'];
        $tab[] = ['title' => '售后驳回', 'url' => url('refund', 'status=-1'), 'value' => '-1'];
        $tab[] = ['title' => '售后收货', 'url' => url('refund', 'status=2'), 'value' => '2'];
        $tab[] = ['title' => '售后回款', 'url' => url('refund', 'status=3'), 'value' => '3'];
        $tab[] = ['title' => '已取消', 'url' => url('refund', 'status=-2'), 'value' => "-2"];
        $this->assign('tab_list', $tab);
        $data_list = RefundModel::getList($map, $order)->each(function($item){            
            $item['status_title']=RefundModel::$status[$item['status']];  
            $item['refund_type_title']=RefundModel::$refundGoodsState[$item['refund_type']];         
            $item['order_type_title']= OrderModel::$orderTypes[$item['order_type']];            
            $item['pay_type_title']= OrderModel::$payTypes[$item['pay_type']] ?? $item['pay_type'];  
            return $item;
        });
    
        $this->assign('list', $data_list);
        $this->assign('pages', $data_list->render());
        $this->assign('orderStatus', [0 => '驳回', 1 => '同意']);
        return $this->fetch();
    }

   
    public function refund_express()
    {
        $rfid = input('param.rfid');
        $order_refund = RefundModel::get($rfid);     
        if(!$order_refund["express_company_id"]){
            $this->error("未发货");
        }
        $express_company = \app\order\model\ExpressCompany::get($order_refund['express_company_id']);
        $order_refund["express_company"] = $express_company["name"] ??  "";
        $this->assign('order_refund', $order_refund);
        $ex =  \app\order\model\OrderGoodsExpress::getQuery($order_refund["express_no"], $express_company["express_no"], $order_refund["order_sn"],$order_refund["receiver_mobile"]);   
        $this->assign('ex', $ex);
        return $this->fetch();
    }

    public function refund_account()
    {
        $rfid = input('param.rfid');
        $order_refund = Db::name('order_refund')->get($rfid);
        $user_account = Db::name('user_withdraw_account')->where(['user_id' => $order_refund['user_id']])->find();
        $this->assign('user_account', $user_account);
        $this->assign('order_refund', $order_refund);
        return $this->fetch();
    }
    
      /**
     * 平台收到退回货物，打款
     * @author php迷途小书童
     * @created 2021/1/26 10:04
     */
    public function refund_change_status()
    {
        $rfid = input('param.rfid');
        $val = input('param.val');//2确认收货 3确认打款
        $nopay = input('param.nopay/d',0);//0自动转账 1标记打款
        $is_defective = input('param.is_defective', 0);
        Db::startTrans();
        try {          
            switch (intval($val)) {
                case 2://确认收货
                    $info = RefundModel::refundReceive($rfid);
                    break;
                 case 3://确认打款
                    $nopay = $nopay == 1 ? 1 : 0;
                    $info = RefundModel::refundPay($rfid,0,$is_defective,$nopay);
                    break;
                default:
                    throw new \Exception("不支持的操作");             
            }    
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }      
        $this->success('确认成功', cookie('__forward__'),"_parent_reload");          
    }


   

     /**
     * 售后原因
     */
    public function refund_detail($rfid)
    {        
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        $detail = RefundModel::getInfo($rfid);
        if(!$detail){
            $this->error("参数错误");
        }
        $detail['status_title'] = RefundModel::$status[$detail['status']];  
        $detail['refund_type_title']=RefundModel::$refundGoodsState[$detail['refund_type']];         
        $detail['order_type_title']= OrderModel::$orderTypes[$detail['order_type']];  
    
        
        $detail['refund_picture'] = get_files_url($detail['refund_picture']);
        $detail["express_company"] = \app\order\model\ExpressCompany::get($detail['express_company_id']);
        // $refundCause = RefundModel::$refundCause;
        // $detail['refund_reason'] = $refundCause[$detail['refund_reason']];
        $this->assign('detail', $detail);
        $info = OrderInfo::get_order_detail($detail['order_sn']);     
        $info['order_status'] = OrderModel::$order_status[$info['status']];
        $info['pay_type']= OrderModel::$payTypes[$info['pay_type']] ?? $info['pay_type'];  
        $this->assign('order_info', $info);
        return $this->fetch();
    }
    
    /**
     * 修改退款金额
     * 
     */
    public function refund_edit_money(){
        $id = input("id",0);
        $money = input("money");
        if(!$id || !$money){
            $this->error("请填写内容");
        }
        if(!is_numeric($money)){
            $this->error("金额格式非法");
        }
        Db::startTrans();
        try{
            RefundModel::editMoney($id, $money);            
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("修改成功"); 
    }

    /**
     * 同意售后
     */
    public function refund_sure($rfid,$nopay = 0)
    {
        if($this->request->isAjax()){
            Db::startTrans();
            try {
                $param = $this->request->post();
                if(!empty($param['county'])){
                    $areas = \app\common\model\Area::getParents($param['county']);
                    $param["receiver_province"] = $areas[0]["name"] ?? "";
                    $param["receiver_city"] = $areas[1]["name"] ?? "";
                    $param["receiver_district"] = $areas[2]["name"] ?? "";
                }
               if(!empty($param['sender_id'])){
                    $sender =   \think\Db::name("goods_express_sender")->get($param['sender_id']);
                    
                    $param["receiver_name"] = $sender["name"] ?? "";
                    $param["receiver_mobile"] = $sender["phone"] ?? "";
                    
                    $param["receiver_province"] = $sender["province"] ?? "";
                    $param["receiver_city"] = $sender["city"] ?? "";
                    $param["receiver_district"] = $sender["area"] ?? "";
                    $param["receiver_address"] = $sender["address"] ?? "";
                }
                $param['county'] = null;
                unset($param['county']);
                $nopay = $nopay == 1 ? 1 : 0;
                RefundModel::refundSure($rfid, 0, 0,$param ?: [] , $nopay);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage(), cookie('__forward__'));
            }
             action_log('order_refund_pass', 'goods', 0, UID);
            $this->success('操作成功', cookie('__forward__'));
        }
        $info = RefundModel::where("id",$rfid)->find();
        if(!$info){
            $this->error("退款单异常");
        }
        $sender_id = OrderModel::where('order_sn',$info["order_sn"])->value("sender_id");
        
        $sender = Db::name("goods_express_sender")->column("id,concat(name,' ',phone,' ',province, city, area,address)");
        $fields = [    
            ["type"=>"select",'name'=>"sender_id",'title'=>"收货地址","extra"=>$sender,"value"=>$sender_id ,'tips'=>'点击<a href="'.url('goods/sender/index').'" target="_blank">管理地址</a>'],
//            ['type' => 'text', 'name' => 'receiver_name', 'title' => '收件人', 'tips' => '请填写收件人姓名'],
//            ['type' => 'text', 'name' => 'receiver_mobile', 'title' => '手机号', 'tips' => '请填写收件人手机号'],
//            ['type' => 'linkages', 'name' => 'county', 'title' => '选择省市区', 'table' =>'china_area', 'level' =>3, 'option' => 'name', 'pid' => 'pid', 'key' => 'id'],
//            ['type' => 'text', 'name' => 'receiver_address', 'title' => '地址', 'tips' => '请填写收货地址,例如：大学路华城国际 1905'],
            ['type' => 'textarea', 'name' => 'receiver_remark', 'title' => '备注', 'tips' => '请填写您的其他信息']   
        ];       
        $this->assign('page_title', '退货通过');      
        $this->assign('form_items', $fields); 
        return $this->fetch('admin@public/add');
    }

    /**
     * 退优惠券
     * */
    public function refund_coupon($coupon_id)
    {
        $coupon = Db::name('operation_coupon_record')->where(['id' => $coupon_id, 'status' => 3])->find();
        if (!$coupon) {
            return ['error' => 1, 'msg' => lang('没有可退的优惠券')];
        }
        $res = Db::name('operation_coupon_record')->where(['id' => $coupon_id])->update(['status' => 1]);
        return ['error' => 0, 'msg' => ''];
    }
     public function delShareMoney($order, $goods_id)
    {
        Db::name("share_seven_day_log")->where(['order_sn' => $order, 'goods_id' => $goods_id])->delete();
    }


    /**
     * 退货拒绝，驳回填写原因
     */
    public function refund_del($rfid)
    {
        if($this->request->isAjax()){
            $refund_reject = input("post.refund_reject","");
            Db::startTrans();
            try {
                RefundModel::cancelOrder($rfid, 0, -1 ,$refund_reject);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage(), cookie('__forward__'));
            }
            action_log('order_refund_refuse', 'goods', 0, UID);
            $this->success('操作成功', cookie('__forward__'));
       }
        $fields = [     
            ['type' => 'textarea', 'name' => 'refund_reject', 'title' => '驳回原因', 'tips' => '请填写驳回的原因']
        ];       
        $this->assign('page_title', '退货驳回');      
        $this->assign('form_items', $fields); 
        return $this->fetch('admin@public/add');
    }
}